<template>
	<view class="container">
		<view class="header" :style="{top: top + 'px',height:height+'px',padding: '0 ' + 30 +'rpx'}">
			<view class="header-left">
				<view class="icon" @click="goBack">
					<u-icon name="arrow-left" color="#30323B" size="22"></u-icon>
				</view>
			</view>
			<view class="header-flex-row">
				<text :class="{title: type === 1}" style="margin-right: 50rpx;" @click="setType(1)">找兴趣</text>
				<text :class="{title: type === 2}" @click="setType(2)">我加入的</text>
			</view>
		</view>

		<view class="gap" :style="{height: top + height +  5  +'px', width: '100%', background: '#fff'}"></view>
		<image :src="img" class="interest-img" mode="widthFix" @load="handleImageLoad" @error="handleImageLoad">
		</image>
		<view class="search">
			<u-search placeholder="请输入关键词搜索" @change="e => init(true)" v-model="name" :showAction="false"
				:clearabled="true" @search="e => init(true)"></u-search>
			<view class="bottom-btn" @click="createCircle" v-if="state == 2">
				创建圈子
			</view>
		</view>
		<view class="interest" :style="{height: `calc(100vh - ${getHeight}px - 10px)`}">
			<scroll-view class="sidebar" scroll-y :scroll-top="sidebarScrollTop">
				<view v-for="(item, index) in indexList" :key="index" class="sidebar-item"
					:class="{ active: activeIndex === index }" @click="handleSidebarClick(index)">
					{{ item }}
				</view>
			</scroll-view>

			<!-- 主内容区 -->
			<scroll-view class="main-content" id="mainContent" scroll-y :scroll-into-view="currentViewId"
				@scroll="onMainScroll">
				<view v-for="(item, index) in contentList" :id="'item' + index" :key="index" class="content-section">
					<view class="scroll-c">
						<view class="section-title">{{ indexList[index] }}</view>
						<!-- 内容列表 -->
						<view class="flex-row flex-warp" v-if="params.name ? false : !item.is_more">
							<view v-for="(subItem, subIndex) in item.defaultData" :key="subIndex"
								class="content-item flex-column-center" @click="open(subItem)">
								<view class="content-img">
									<image :src="subItem.logo" mode="aspectFill" alt="" class="content-img-item">
									</image>
									<view class="content-img-sh" v-if="subItem.audit_status === 0">审核中</view>
									<view class="content-img-add" v-else-if="subItem.does_it_exist">已加入</view>

								</view>

								<!-- <view class="content-img"></view> -->
								<view class="content-title">{{ subItem.name }}</view>
								<view class="content-count">{{getNumTx(subItem.num_people)}} 成员</view>
							</view>
						</view>
						<view class="flex-row flex-warp" v-else>
							<view v-for="(subItem, subIndex) in item.list" :key="subIndex"
								class="content-item flex-column-center" @click="open(subItem)">
								<view class="content-img">
									<image :src="subItem.logo" mode="aspectFill" alt="" class="content-img-item">
									</image>
									<view class="content-img-sh" v-if="subItem.audit_status === 0">审核中</view>
									<view class="content-img-add" v-else-if="subItem.does_it_exist">已加入</view>
								</view>
								<!-- <view class="content-img"></view> -->
								<view class="content-title">{{ subItem.name }}</view>
								<view class="content-count">{{getNumTx(subItem.num_people)}} 成员</view>
							</view>
						</view>
						<view class="more" @click="setIsMore(index)"
							v-if="(item.list.length != item.defaultData.length) && item.defaultData.length > 0">
							<view>
								<text>{{item.is_more ? '收起' : '展开'}}</text>
								<u-icon name="arrow-down" color="#000" size="10" v-if="!item.is_more"></u-icon>
								<u-icon name="arrow-up" color="#000" size="10" v-else></u-icon>
							</view>
						</view>
						<u-gap :height="10" v-if="item.defaultData.length === 0"></u-gap>
					</view>

				</view>
				<view style="width: 100%;height: 170rpx;"></view>
			</scroll-view>

			<!-- 滑动提示框 -->
			<!-- <view v-if="touchActive" class="index-popup">
				{{ indexList[currentTouchIndex] }}
			</view> -->
		</view>


		<MemberPopupVue ref="MemberPopupVueRef" @reload="payReload" />
		<u-modal :show="modalshow" :closeOnClickOverlay="true" confirmText='找兴趣' confirmColor='#12B475'
			cancelColor='#333333' showCancelButton=true cancelText='联系圈主' :title="modaltitle" :content='modalcontent'
			@confirm='modalcomfim' @cancel='modalcancel' @close="()=>modalshow=false"></u-modal>
	</view>
</template>

<script>
	import {
		throttle
	} from '@/common/util.js'
	import {
		circle_list,
		i_joined_circle_list,
		recently_visited_circle,
		circle_host_id
	} from '@/common/http/api.js'
	import MemberPopupVue from './memberPopup/memberPopup.vue'
	export default {
		components: {
			MemberPopupVue
		},
		data() {
			return {
				modalshow: false,
				modaltitle: '',
				modalcontent: '圈主正在审核您的名片······',
				indexList: [], // 索引列表
				contentList: [],
				activeIndex: 0, // 当前激活索引
				currentViewId: '', // 当前滚动锚点
				touchActive: false, // 是否正在触摸
				currentTouchIndex: 0, // 触摸点索引
				sidebarScrollTop: 0, // 侧边栏滚动位置（防抖动
				top: 0,
				height: 0,
				mainRect: '',
				cancelid: '',
				img: '',
				type: 1, // 1找兴趣 2我加入的
				is_prevent: false,
				params: {
					name: undefined
				},
				name: '',
				state: 2, //1 首页进去 不需要创建
				divInfo: {
					search: 0,
					img: 0
				}
			}
		},
		created() {
			// 获取胶囊按钮的位置信息
			let menuButtonRect = wx.getMenuButtonBoundingClientRect();
			this.top = menuButtonRect.top

			this.height = menuButtonRect.height

		},
		computed: {
			getHeight() {
				return this.height + this.divInfo.search + this.divInfo.img + this.top
			}
		},
		mounted() {

		},
		onLoad(e) {
			if (e.type) {
				this.state = e.type
			}


		},
		onShow() {
			this.init()
		},
		methods: {
			handleImageLoad() {
				const query = uni.createSelectorQuery().in(this);
				query.select('#mainContent').boundingClientRect(mainRect => {
					if (mainRect) {
						this.mainRect = mainRect
					}
				}).exec();
				query.select('.interest-img').boundingClientRect(mainRect => {
					if (mainRect) {

						this.divInfo.img = mainRect.height
					}
				}).exec();
				query.select('.search').boundingClientRect(mainRect => {
					if (mainRect) {

						this.divInfo.search = mainRect.height + 10
					}
				}).exec();
			},
			payReload(row) {
				uni.navigateTo({
					url: '/pages/index/addCard?id=' + row.id + '&name=' + row.name + '&type=' + this.state
				})
			},

			modalcancel() {
				uni.showLoading()
				circle_host_id({
					circle_id: this.cancelid
				}).then(res => {
					uni.hideLoading()
					if (res.data.b_id) {
						uni.navigateTo({
							url: '/pages/index/other?shareId=' + res.data.b_id
						})
					} else {
						this.$u.toast('该圈暂无圈主！')
					}
				})
			},
			modalcomfim() {
				this.modalshow = false
			},
			open(row) {

				if (row.audit_status === 0) {
					// this.$u.toast('待审核中！')

					this.modalshow = true
					this.modaltitle = row.name
					this.cancelid = row.id
					return

					uni.showModal({
						title: row.name,
						content: `圈主正在审核您的名片······`,
						showCancel: true,
						cancelText: '联系圈主',
						confirmText: '找兴趣',
						confirmColor: '#12B475',
						success: res => {
							if (res.confirm) {

							} else if (res.cancel) {
								uni.showLoading()
								circle_host_id({
									circle_id: row.id
								}).then(res => {
									uni.hideLoading()
									if (res.data.b_id) {
										uni.navigateTo({
											url: '/pages/index/other?shareId=' + res.data.b_id
										})
									} else {
										this.$u.toast('该圈暂无圈主！')
									}
								})
							}
						}
					});
					return
				}
				if (row.does_it_exist === 0) {
					//未加入
					if (row.permission.includes('4')) {
						//加入付费逻辑
						if (row.user_circle_pay === 1) {
							//已付费过
							if (row.type === 1) {
								//兴趣圈
								uni.navigateTo({
									url: '/pages/index/addCard?id=' + row.id + '&type=' + this.state
								})
							} else {
								uni.navigateTo({
									url: '/pages/index/addCard?id=' + row.id + '&name=' + row.name + '&type=' +
										this.state
								})
							}
						} else {
							//未付费
							//判断是否开启付费圈子
							//判断是否是企业
							if (row.type != 1 && Array.isArray(row.circle_pay) && row.circle_pay.length > 0) {
								//需要付费
								//打开弹窗
								this.$refs.MemberPopupVueRef.show(row)
							} else {
								//兴趣圈
								uni.navigateTo({
									url: '/pages/index/addCard?id=' + row.id + '&type=' + this.state
								})
							}
						}
					} else {
						//已付费过
						if (row.type === 1) {
							//兴趣圈
							uni.navigateTo({
								url: '/pages/index/addCard?id=' + row.id + '&type=' + this.state
							})
						} else {
							uni.navigateTo({
								url: '/pages/index/addCard?id=' + row.id + '&name=' + row.name + '&type=' + this
									.state
							})
						}
					}



				} else {
					//已加入
					uni.showLoading()
					recently_visited_circle({
						id: row.id
					}).then(res => {
						uni.hideLoading()
						uni.switchTab({
							url: '/pages/circle/circle'
						})
					})
				}
			},
			setType(type) {
				this.type = type;
				this.contentList = [];
				this.indexList = []
				this.activeIndex = 0;
				// 更新侧边栏滚动位置
				this.sidebarScrollTop = 0;

				this.params.name = undefined
				this.init()
			},
			setIsMore(index) {

				this.contentList[index].is_more = !this.contentList[index].is_more
				this.$forceUpdate()
			},
			getNumTx(num) {
				if (!num) {
					return 0
				}
				num = Number(num)
				if (num > 1000) {
					return (num / 1000).toFixed(1) + 'k'
				}
				return num
			},
			init(e) {
				if (e) {
					this.params.name = this.name
				}
				let http = this.type === 1 ? circle_list : i_joined_circle_list
				http(this.params).then(res => {
					this.img = res.data.img

					res.data.list.forEach(i => {
						i.is_more = false
						if (Array.isArray(i.list)) {
							if (this.type === 1) {
								i.defaultData = i.list.filter(i => i.fold === 1)
							} else {
								i.defaultData = i.list
							}

						}
					})
					this.indexList = res.data.list.map(i => i.name)
					this.contentList = res.data.list
				})
			},
			//返回上一级
			goBack() {

				uni.navigateBack()
			},
			rightClick() {

			},
			// 点击侧边栏
			handleSidebarClick(index) {

				this.activeIndex = index;
				this.currentViewId = `item${index}`;
				this.is_prevent = true
				setTimeout(() => {
					this.is_prevent = false
				}, 500)

			},
			// 主内容区滚动监听
			onMainScroll(e) {
				if (this.is_prevent) return;
				const scrollTop = e.detail.scrollTop;
				this.getFirstVisibleSectionTitle(scrollTop);
			},
			// 获取第一个可见的 section-title 元素
			getFirstVisibleSectionTitle: throttle(function(scrollTop) {
				const query = uni.createSelectorQuery().in(this);
				query.selectAll('.scroll-c').boundingClientRect(rects => {

					if (rects && rects.length > 0) {
						let newActiveIndex = -1;
						for (let i = 0; i < rects.length; i++) {
							const rect = rects[i];
							//元素顶部在可视窗口
							if (rect.top >= this.mainRect.top && rect.top <= this.mainRect.bottom) {
								newActiveIndex = i;
								break;
							} else if (rect.top <= this.mainRect.top && rect.bottom >= this.mainRect.top) {
								newActiveIndex = i;
								break;
							}
						}
						if (newActiveIndex !== -1 && newActiveIndex !== this.activeIndex) {

							if (newActiveIndex === 0) {
								this.activeIndex = 0;
								// 更新侧边栏滚动位置
								this.sidebarScrollTop = this.activeIndex * 40; // 80 是侧边栏项的高度
							} else {
								this.activeIndex = newActiveIndex;
								// 更新侧边栏滚动位置
								this.sidebarScrollTop = this.activeIndex * 40; // 80 是侧边栏项的高度
							}
						}
					}
				}).exec();
			}, 10),
			createCircle() {
				uni.navigateTo({
					url: '/pagesA/beforeCreateCircle/beforeCreateCircle'
				})
			}
		}
	}
</script>

<style lang="scss" scoped>
	::v-deep .u-modal__content {
		padding-top: 42rpx !important;
	}

	.container {

		position: relative;

		.bottom-btn {
			background: #12B475;
			width: 200rpx;
			height: 64rpx;
			border-radius: 34rpx;
			color: #fff;
			font-weight: bold;
			font-size: 28rpx;
			line-height: 64rpx;
			text-align: center;
			margin-left: 30rpx;

		}

		.title {
			// margin-left: 50rpx;
			font-weight: bold;
		}

		.navbar-placeholder {
			height: 130rpx;
		}

		.interest-img {
			width: 100%;

			//background-color: red;
		}

		.interest {
			display: flex;
			//height: calc(100vh - 200rpx);
		}

		.list-cell {
			display: flex;
			box-sizing: border-box;
			width: 100%;
			padding: 10px 24rpx;
			overflow: hidden;
			color: #323233;
			font-size: 14px;
			line-height: 200rpx;
			background-color: #fff;
		}

		.sidebar {
			width: 150rpx;
			background-color: #f5f5f5;
			padding: 0rpx 0 20rpx;
		}

		.sidebar-item {
			height: 60rpx;
			line-height: 60rpx;
			text-align: center;
			font-size: 26rpx;
			font-weight: bold;
			color: #666;
			overflow: hidden;
			// text-overflow: ellipsis;
			// white-space: nowrap;
			padding: 10rpx 35rpx;
		}

		.sidebar-item.active {
			background-color: #fff;
			color: #121212;
			font-weight: bold;
		}

		.main-content {
			flex: 1;
			padding: 0 20rpx;
		}

		.content-section {
			margin-bottom: 30rpx;
			border-bottom: 1rpx solid #eee;
		}

		.section-title {
			font-size: 32rpx;
			padding: 20rpx;
		}

		.content-item {
			padding: 20rpx;
			text-indent: 0em;
		}

		.content-img {
			width: 100rpx;
			height: 100rpx;
			border-radius: 10rpx;
			background-color: #666;
			position: relative;

			image {
				width: 100%;
				height: 100%;
				border-radius: 10rpx;
			}

			.content-img-add {
				position: absolute;
				bottom: -1rpx;
				left: 0;
				z-index: 2;
				background: lightgreen;
				color: #fff;
				font-size: 22rpx;
				text-align: center;
				width: 100%;
				border-bottom-right-radius: 10rpx;
				border-bottom-left-radius: 10rpx;
			}

			.content-img-sh {
				position: absolute;
				bottom: -1rpx;
				left: 0;
				z-index: 2;
				background: #f9ae3d;
				color: #fff;
				font-size: 22rpx;
				text-align: center;
				width: 100%;
				border-bottom-right-radius: 10rpx;
				border-bottom-left-radius: 10rpx;
			}
		}

		.content-title {
			font-size: 26rpx;
			text-align: center;
			font-weight: bold;
		}

		.content-count {
			font-size: 20rpx;
			color: #999;

		}

		.index-popup {
			position: fixed;
			top: 50%;
			left: 50%;
			transform: translate(-50%, -50%);
			width: 120rpx;
			height: 120rpx;
			background: rgba(0, 0, 0, 0.7);
			border-radius: 16rpx;
			color: white;
			font-size: 48rpx;
			text-align: center;
			line-height: 120rpx;
		}


	}

	.header {
		display: flex;
		position: fixed;
		z-index: 150;
		justify-content: center;
		align-items: center;
		box-sizing: border-box;
		background: #fff;
		width: 100vw;

		.header-left {
			position: absolute;
			left: 0;
			top: 6px;
		}

		.header-flex-row {
			width: fit-content;

		}
	}

	.more {
		width: 100%;
		padding-bottom: 20rpx;

		&>view {
			padding: 0 10px;
			font-size: 22rpx;
			display: flex;
			align-items: center;
			justify-content: center;

			&>text {
				margin-right: 10rpx;
			}
		}

	}

	.search {
		width: 100%;
		box-sizing: border-box;
		padding: 0 30rpx;
		margin: 10rpx 0;
		display: flex;
		align-items: center;

	}
</style>